< previous page page_492 next page >

Page 492
Creating Application and Document Objects
The two most important Word objects you need to know about are the Word.Application and Word.Document objects, which provide access to instances of the Word application and Word documents, respectively.
To launch Word from Visual Basic code, simply create a new instance of the Word.Application object, as you would with any other object:
Dim objWord As Word.Application
Set objWord = New Word.Application
Here, notice that early binding is used with the Set statement, which makes programming with objects easier, as discussed in Chapter 16, "Classes: Reusable Components."
sarrow.gifSee "Declaring and Using Objects," p. 366
The preceding two lines of code launch Word on your PC. Word then appears on the task list, but it remains invisible until you set the object's Visible property to True, as in the following example:
objWord.Visible = True
You can also create Word.Document objects from the application object. The Word.Application object contains a Documents collection. Recall from Chapter 13 that you can use the Add method of a collection to add new objects.
open.gif Now you can try a simple example. First, start a new Standard EXE project in Visual Basic and reference the Word Object Library as previously described. Next, add two command buttons, cmdStart and cmdClose, and enter the code from Listing 22.1 in the form.
Listing 22.1 WORDDEMO.TXTUsing Word from Visual Basic
Dim objWord As Word.Application

Private Sub cmdStart_Click()
    Dim objDoc As Word.Document

    'Start Word and make it visible
    Set objWord = New Word.Application
    objWord.Visible = True

    'Create a new document
    Set objDoc = objWord.Documents.Add

    'Make it the active document
    objDoc.Activate

    'Add some text to the document
    objDoc.ActiveWindow.Selection.InsertAfter "This is some text"
    objDoc.ActiveWindow.Selection.InsertParagraphAfter
    objDoc.ActiveWindow.Selection.InsertAfter "This is some more text."
    objDoc.ActiveWindow.Selection.InsertParagraphAfter

 
< previous page page_492 next page >